<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>矩形进度条效果</title>
  <style>
    .box {
      position: absolute;
      top: 40px;
      left: 50%;
      transform: translateX(-50%);
      background-color: #eee;
      border-radius: 5px;
    }
  </style>
</head>
<body>
  <svg class="box" width="800" height="20">
    <!-- 定义一个线性渐变色 -->
    <defs>
      <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
        <stop offset="0%" style="stop-color:rgb(57, 242, 218);stop-opacity:1" />
        <stop offset="50%" style="stop-color:rgb(6, 166, 230);stop-opacity:1" />
        <stop offset="100%" style="stop-color:rgb(12, 78, 245);stop-opacity:1" />
      </linearGradient>
    </defs>
    <!-- 将线性渐变色绑定到矩形的 fill 背景色上 -->
    <rect class="rect" width="0" height="20" rx="5" ry="5" fill="url(#grad1)"></rect>
    <text class="text" x="400" y="12" fill="red" text-anchor="middle" alignment-baseline="middle">0%</text>
  </svg>
  <script>
    const rect = document.querySelector('.rect')
    const text = document.querySelector('.text')
    let rectWidth = 80   // 矩形的宽度，即停止动画的值 单位: 百分比
    let loadingWidth = 0    // 进度条开始时的初始值
    // 此类场景使用 window.requestAnimationFrame() 进行循环比使用定时器性能更好
     let timer = window.requestAnimationFrame( function fn() {
      // 循环继续的条件
      if(loadingWidth < rectWidth) {
        loadingWidth += 0.5   // 加的越小动画持续时间越长
        rect.style.width = loadingWidth + '%'
        text.innerHTML = loadingWidth.toFixed() + '%'
        // 继续循环则递归调用 fn 函数
        timer = window.requestAnimationFrame(fn)
      } else {
        // 循环停止
        rect.style.width = rectWidth + '%'
        // 清除定时器
        window.cancelAnimationFrame(timer)
      }
    })


  </script>
</body>
</html>